// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, InteractionManager, StyleSheet, WebView } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import Icon from 'react-native-vector-icons/Ionicons';
import EZSwiper from 'react-native-ezswiper';
import { Actions } from 'react-native-router-flux';
import FitImage from 'react-native-fit-image';

// antd 按需加载
import { Tabs, Toast, Portal, Stepper, WhiteSpace, List, Modal } from '@ant-design/react-native';
const Item = List.Item;
const Brief = Item.Brief;

// 引入 处理数据 所需文件
import { goodsDetail, goodsAttribute, shopCartAdd, goodsAppraiseList, goodsCollection, cardGoodsList } from '../../module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, CacheImage, Rating, Results, Attribute, CardPost, Layout } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { merchantsDefault, background } from '../../util/images'
import { press, size, ScreenWidth, ScreenHeight, pathHead, path, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage, ImageFileSave, WeChatShareToSession } from '../../util/utils.js'

class AgentGoodDetails extends Component {
  render() {
    return null
  }

  constructor(props) {
    super(props)
    this.state = {
      goodDetail: {},
      goodAttribute: [],
      goodAppraiseList: {},
      detailModule: '1',
      swiperIndex: 0,
      attributeVisible: false,
      goodsNumber: 1,
      height: 0,
      cardGoodsList: []
    }
  }

  componentDidMount() {
    const { goodsId, productId } = this.props
    this.loading = Toast.loading('加载中')
    InteractionManager.runAfterInteractions(() => {
      // ...耗时较长的同步的任务...
      this.initData({ goodsId, productId })
    });
  }

  handleCloseToase() {
    // if (this.loadingIndex >= 3) {
    //   Portal.remove(this.loading)
    // }
  }

  initData({ goodsId, productId }) {
    // this.loading = Toast.loading('加载中')
    goodsDetail({ goodsId: goodsId }).then(res => {
      console.log(res)
      // this.loadingIndex++
      // this.handleCloseToase()
      Portal.remove(this.loading)
      this.setState({
        goodDetail: res.data
      }, () => {
        goodsAttribute({ goodsId: goodsId, productId }).then(goodsAttributeRes => {
          console.log(goodsAttributeRes)
          // this.loadingIndex++
          // this.handleCloseToase()
          this.setState({
            goodAttribute: goodsAttributeRes.data
          })
        })
        goodsAppraiseList({ current: 1, productId, size: 5 }).then(goodsAppraiseListRes => {
          // this.loadingIndex++
          // this.handleCloseToase()
          this.setState({
            goodAppraiseList: goodsAppraiseListRes.data
          })
        })
        cardGoodsList({ current: 1, goodsId, size: 1 }).then(cardGoodsListRes => {
          // this.loadingIndex++
          // this.handleCloseToase()
          this.setState({
            cardGoodsList: cardGoodsListRes.data
          })
        })
      })
    }).finally(() => {
      Portal.remove(this.loading)
    })
  }

  componentWillReceiveProps(nextProps) {
    // 假设前一个页面传递过来一个名字叫做isRefresh的布尔型参数
    console.log(nextProps)
    if (this.props.goodsId != nextProps.goodsId && nextProps.refresh) {
      this.initData({ goodsId: nextProps.goodsId, productId: nextProps.productId })
    }
    //需要刷新的数据可以做
  }

  goodsCollection() {
    const { goodsId, productId } = this.props

  }

  changeDetailModule(detailModule) {
    this.setState({
      detailModule
    })
  }

  touristBillGood() {
    const { goodsId, productId } = this.props
    console.log(`${path}/tourist/bill/${goodsId}`)
    WeChatShareToSession({
      type: 'imageFile',
      title: 'image file download from network',
      description: 'share image file to time line',
      mediaTagName: 'email signature',
      messageAction: undefined,
      messageExt: undefined,
      imageUrl: `${path}/tourist/bill/${goodsId}` // require the prefix on both iOS and Android platform
    }).then(shareRes => {
      console.log(shareRes)
    }).catch(error => {
      console.log(error)
    })
  }


  renderSwiper() {
    const { swiperIndex, goodDetail } = this.state
    const width = ScreenWidth
    return (
      <View style={{}}>
        <EZSwiper
          //设置属性          
          style={{ width: width, height: ScreenWidth }}
          renderRow={this.renderRow}
          width={width}
          height={ScreenWidth}
          loop={false}
          dataSource={goodDetail.goodsImages.map((item, index) => index)}
          cardParams={{ cardSide: width, cardSmallSide: ScreenWidth, cardSpace: 0 }}
          onWillChange={this.onIndexChanged}
        />
        <View style={{
          position: "absolute",
          left: 0,
          right: 0,
          bottom: 10,
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
        }}>
          {goodDetail.goodsImages.map((item, index) => {
            if (swiperIndex == index) {
              return <View key={index} style={{ backgroundColor: '#fff', width: 16, height: 8, borderRadius: 4, margin: 3, }} />
            } else {
              return <View key={index} style={{ backgroundColor: 'rgba(255,255,255,.2)', width: 8, height: 8, borderRadius: 4, margin: 3, }} />
            }
          })}
        </View>
      </View>
    )
  }

  renderRow = (currentItem, dataSourceIndex) => {
    const { goodDetail } = this.state
    let item = goodDetail.goodsImages[dataSourceIndex]
    let width = ScreenWidth
    let height = ScreenWidth
    return (
      <TouchableOpacity
        onPress={() => {
          // press(() => Actions.merchants({ shopnum: item.app_link }))
        }}
        style={{
          height: height,
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'row',

        }}
      >
        <CacheImage
          resizeMode='cover'
          style={{
            width: width,
            height: height,
            overflow: 'hidden'
          }}
          source={{ uri: `${pathHead}${item.imageUrl}` }}

        />
      </TouchableOpacity>
    )
  }

  onIndexChanged = (item, index) => {
    this.setState({
      swiperIndex: index
    })
  }

  renderGoodDetail() {
    const { goodDetail, goodAppraiseList, cardGoodsList } = this.state
    const { productId } = this.props

    if (goodDetail && goodDetail.goods) {
      return (
        <View>
          {this.renderSwiper()}
          <View style={{
            padding: 15
          }}>
            <View style={{
              flexDirection: 'row',
              alignItems: 'flex-end',
              justifyContent: 'space-between',
              marginBottom: 5
            }}>
              <View style={{
                flexDirection: 'row',
                alignItems: 'flex-end',
              }}>
                <Text style={{ fontSize: 27, color: '#000000', lineHeight: 30, fontWeight: 'bold', marginLeft: -10 }}>￥{goodDetail.goods.goodsPrice}</Text>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 30, textDecorationLine: 'line-through', fontWeight: 'bold', marginLeft: 20 }}>￥{goodDetail.goods.marketPrice}</Text>
              </View>
              <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginLeft: 20,
                marginRight: 20,
              }}>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 30, }}>CV</Text>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 30, }}>{goodDetail.goods.cv}</Text>
              </View>
              <TouchableOpacity onPress={() => this.touristBillGood()}>
                <View style={{}}>
                  <Icon name="md-open" size={22} color="#61676F" />
                </View>
              </TouchableOpacity>
            </View>
            <View style={{
              flexDirection: 'row',
              alignItems: 'center',
              marginBottom: 10
            }}>
              <Text style={{ fontSize: 16, color: '#333', lineHeight: 24, fontWeight: 'bold', }}>{goodDetail.goods.goodsName}</Text>
            </View>
            {/* <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginBottom: 10
              }}>
                <Text style={{ fontSize: 14, color: '#333', lineHeight: 18, marginRight: 20 }}>{goodDetail.goods.goodsNo}</Text>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{goodDetail.goodsAttribute}</Text>
              </View> */}
            <View style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              marginBottom: 10
            }}>
              <Text style={{ fontSize: 12, color: '#999', lineHeight: 18, marginRight: 20 }}>商品编码 {goodDetail.goods.goodsNo}</Text>
              <Text style={{ fontSize: 16, color: '#999', lineHeight: 18, }}>销量 {goodDetail.goods.saleVolume}</Text>
            </View>
          </View>
          <View style={{ height: 10, backgroundColor: '#e8e8ed' }} />
          <List >
            {/* <Item arrow="horizontal" onPress={this.openAttributeModal}>
              <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                <Text style={{ fontSize: 12, color: '#999', width: 35, lineHeight: 16 }}>已选</Text>
                <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{goodDetail.goodsAttribute}</Text>
              </View>
            </Item> */}
            <Item >
              <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                <Text style={{ fontSize: 12, color: '#999', width: 35, lineHeight: 16 }}>库存</Text>
                <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{goodDetail.goods.stock}个</Text>
              </View>
            </Item>
            <Item >
              <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                <Text style={{ fontSize: 12, color: '#999', width: 35, lineHeight: 16 }}>赠送积分</Text>
                <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{goodDetail.goods.freePoint}</Text>
              </View>
            </Item>
          </List>
          <View style={{ height: 10, backgroundColor: '#e8e8ed' }} />
          <List >
            <Item arrow="horizontal" onPress={() => Actions.appraise({ productId })}>
              <Text style={{ fontSize: 16, color: '#333', lineHeight: 18, }}>评价</Text>
            </Item>
          </List>
          {goodAppraiseList && goodAppraiseList.records && goodAppraiseList.records.map((item, index) => {
            return (
              <View
                key={index}
                style={{
                  marginLeft: 15,
                  paddingRight: 15,
                  paddingVertical: 10,
                  borderBottomColor: '#e5e5e5',
                  borderBottomWidth: .5
                }}
              >
                <View style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  marginBottom: 8
                }}>
                  <CacheImage
                    resizeMode='cover'
                    style={{
                      width: 24,
                      height: 24,
                      overflow: 'hidden',
                      borderRadius: 12,
                      marginRight: 10
                    }}
                    source={{ uri: `${pathHead}${item.avatar}` }}

                  />
                  <Text style={{ fontSize: 12, color: '#333', lineHeight: 16, marginRight: 10 }}>{item.nickname}</Text>
                  <Rating rating={item.score}></Rating>
                  <Text style={{ flex: 1, fontSize: 12, color: '#999', lineHeight: 16, textAlign: 'right' }}>{item.createTime}</Text>
                </View>
                <View style={{ marginVertical: 3 }}>
                  <Text style={{ fontSize: 14, color: '#333', lineHeight: 21, }}>{item.content}</Text>
                </View>
                <View style={{ marginTop: 8 }}>
                  {item.imageList.map((imageListItem, imageListIndex) => {
                    return (
                      <CacheImage
                        key={imageListIndex}
                        resizeMode='cover'
                        style={{
                          width: (ScreenWidth - 30 - 30) / 4 - 2,
                          height: (ScreenWidth - 30 - 30) / 4 - 2,
                          marginRight: 15,

                        }}
                        source={{ uri: `${pathHead}${imageListItem.url}` }}

                      />
                    )
                  })}
                </View>
              </View>
            )
          })}
          {goodAppraiseList && !goodAppraiseList.records && <Results type='data' width={size(500)} height={size(200)} />}
          {goodAppraiseList && goodAppraiseList.records <= 0 && <Results type='data' width={size(500)} height={size(200)} />}
          <View style={{ height: 10, backgroundColor: '#e8e8ed' }} />
          <List >
            {/* <Item arrow="horizontal" onPress={() => Actions.appraise({ productId })}> */}
            <Item >
              <Text style={{ fontSize: 16, color: '#333', lineHeight: 18, }}>相关帖子</Text>
            </Item>
          </List>
          {cardGoodsList && cardGoodsList.records && cardGoodsList.records.map((item, index) => {
            return (
              <CardPost
                key={index}
                data={item}
                hideNav
                handleCardLike={(option) => { }}
              />
            )
          })}
          {cardGoodsList && !cardGoodsList.records && <Results type='data' width={size(500)} height={size(200)} />}
          <View style={{ height: 10, backgroundColor: '#e8e8ed' }} />
        </View>
      )
    }
  }

  openAttributeModal = () => {
    this.setState({
      attributeVisible: true
    })
  }

  closeAttributeModal = () => {
    this.setState({
      attributeVisible: false
    })
  }

  render() {
    const { goodDetail, detailModule, goodsNumber, height } = this.state
    const { goodsId, productId, goodType } = this.props

    return (
      <Layout
        style={{ backgroundColor: '#fff' }}
        header={<Status />}
        footer={
          <View style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}>
            <TouchableOpacity
              style={{
                flex: 1,
                height: 52,
                backgroundColor: '#000000'
              }}
              onPress={() => {
                // Toast.info('该功能未开放', 1)
                Actions.submitAgentOrder({
                  goodsId: goodsId,
                  totalMoney: goodDetail.goods.goodsPrice
                })
              }}>
              <Text style={{ fontSize: 14, color: '#fff', lineHeight: 52, textAlign: 'center' }}>立即购买</Text>
            </TouchableOpacity>
          </View>
        }
      >
        <NavBar
          title="商品详情"
          back
        />
        {/* <View style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}>
            <TouchableOpacity
              style={detailModule == 1 ? activeDetailModule.touch : defaultDetailModule.touch}
              onPress={() => {
                this.changeDetailModule(1)
              }}
            >
              <View style={detailModule == 1 ? activeDetailModule.view : defaultDetailModule.view}>
                <Text style={detailModule == 1 ? activeDetailModule.text : defaultDetailModule.text}>商品介绍</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              style={detailModule == 3 ? activeDetailModule.touch : defaultDetailModule.touch}
              onPress={() => {
                this.changeDetailModule(3)
              }}
            >
              <View style={detailModule == 3 ? activeDetailModule.view : defaultDetailModule.view}>
                <Text style={detailModule == 3 ? activeDetailModule.text : defaultDetailModule.text}>商品评价</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              style={detailModule == 2 ? activeDetailModule.touch : defaultDetailModule.touch}
              onPress={() => {
                this.changeDetailModule(2)
              }}
            >
              <View style={detailModule == 2 ? activeDetailModule.view : defaultDetailModule.view}>
                <Text style={detailModule == 2 ? activeDetailModule.text : defaultDetailModule.text}>图文详情</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              style={detailModule == 4 ? activeDetailModule.touch : defaultDetailModule.touch}
              onPress={() => {
                this.changeDetailModule(4)
              }}
            >
              <View style={detailModule == 4 ? activeDetailModule.view : defaultDetailModule.view}>
                <Text style={detailModule == 4 ? activeDetailModule.text : defaultDetailModule.text}>相关专题</Text>
              </View>
            </TouchableOpacity>
          </View> */}
        <ScrollView style={Style.content}>
          {this.renderGoodDetail()}
          {/* {this.renderAttribute()} */}
          <View style={{ paddingVertical: 10 }}>
            {goodDetail && goodDetail.product &&
              (
                <WebView
                  style={{
                    width: ScreenWidth,
                    height: this.state.height,
                    backgroundColor: 'transparent'
                  }}
                  injectedJavaScript={'setInterval(() => {window.parent.postMessage(document.getElementById("content").clientHeight)}, 500)'}
                  automaticallyAdjustContentInsets={true}
                  source={{
                    html: `
                      <!DOCTYPE html>
                      <html>
                      <style type="text/css">
                          .tour_product_explain img {
                              display: block !important;
                              vertical-align: top !important;
                              width: 100% !important;
                          }
                          .tour_product_explain p {
                              width: 100% !important;
                          }
                      </style>

                      <body>
                          <div class='tour_product_explain' id='content'>${goodDetail.product.productInfo}</div>
                      </body>

                      </html>
                      `
                  }}
                  useWebKit={true}
                  scalesPageToFit={true}
                  javaScriptEnabled={true} // 仅限Android平台。iOS平台JavaScript是默认开启的。
                  domStorageEnabled={true} // 适用于安卓a
                  scrollEnabled={false}
                  onMessage={(event) => {
                    this.setState({ height: +event.nativeEvent.data })
                  }}
                />
              )
            }
          </View>
        </ScrollView>
      </Layout>
    );
  }
}

// class HnaldeLive extends Component {

//   constructor(props) {
//     super(props)
//     this.state = {
//       like: props.like || false
//     }
//   }

//   goodsCollection(like) {
//     const { goodsId, productId } = this.props
//     this.setState({
//       like: !like
//     })
//     goodsCollection({ id: goodsId, type: !like ? 1 : 0 }).then(res => {

//     })
//   }

//   render() {
//     const { like } = this.state
//     return (
//       <TouchableOpacity
//         style={{
//           alignItems: 'center',
//           justifyContent: 'center',
//           height: 51,
//           width: 60,
//         }}
//         onPress={() => {
//           this.goodsCollection(like)
//         }}
//       >
//         <Icon name="ios-heart" size={22} color={like ? '#E5C67B' : '#61676F'} />
//         <Text style={{ fontSize: 10, color: '#61676F', lineHeight: 12, }}>收藏</Text>
//       </TouchableOpacity>
//     )
//   }
// }

export default connect(({ user }) => ({
  user,
}))(pureRender(AgentGoodDetails))
